package com.xinqi.modules.third.service.impl;

import com.xinqi.common.base.response.R;
import com.xinqi.common.core.utils.StringUtils;
import com.xinqi.common.third.wx.help.WxHelp;
import com.xinqi.common.third.wx.util.WxUtils;
import com.xinqi.modules.third.service.WxService;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * 微信相关 服务层实现
 * @author dzy
 */
@Log4j2
@Service
@RequiredArgsConstructor
public class WxServiceImpl implements WxService {

    private final WxHelp wxHelp;

    @Override
    public R getConfig(String url) {
        Map<String, Object> wxInfo = new HashMap<>();
        try {
            String accessToken = wxHelp.getToken();
            if (StringUtils.isNotEmpty(accessToken)) {
                String jsapiTicket = wxHelp.getJsapiTicket(accessToken);
                String noncestr = UUID.randomUUID().toString().replace("-", "").substring(0, 16);//随机字符串
                String timestamp = String.valueOf(System.currentTimeMillis() / 1000);// 时间戳
                //将字符串进行sha1加密
                String signature = WxUtils.sign(jsapiTicket, noncestr, timestamp, url);
                //微信appId
                String appId = wxHelp.getAppId();
                wxInfo.put("appId", appId);
                wxInfo.put("accessToken", accessToken);
                wxInfo.put("jsapi_ticket", jsapiTicket);
                wxInfo.put("timestamp", timestamp);
                wxInfo.put("nonceStr", noncestr);
                wxInfo.put("signature", signature);
                return R.ok(wxInfo);
            }else {
                return R.fail("accessToken获取失败");
            }
        } catch (Exception e) {
            return R.fail("加密失败");
        }
    }

}
